package com.topten.dao.especificos;

import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import com.topten.basicas.seguranca.Usuario;
import com.topten.basicas.varejo.Cliente;
import com.topten.dao.generico.DAOGenerico;
import com.topten.negocio.CpfJaCadastradoException;

public class DAOCliente extends DAOGenerico<Cliente> implements IDAOCliente {
	
	public Cliente buscarClientePorCpf(String cpf){
		try{
			this.entityManager.getTransaction().begin();
			TypedQuery<Cliente> query = entityManager.createQuery("select c from Cliente c where c.documento1 = :cpfc", Cliente.class);			
			query.setParameter("cpfc", cpf);
			this.entityManager.getTransaction().commit();
			return query.getSingleResult();
		}catch(Exception ex){
			ex.printStackTrace();
			if(entityManager.getTransaction() != null && entityManager.getTransaction().isActive()){
				entityManager.getTransaction().rollback();
			}
		}
		return null;
	}
	
	public final void inserirObjetos(Cliente cliente, Usuario usuario) throws CpfJaCadastradoException {
		EntityTransaction tx = getEntityManager().getTransaction();		
		try {
			tx.begin();
			getEntityManager().persist(usuario);
			getEntityManager().persist(cliente);			
			tx.commit();
			System.out.println(classePersistente.getSimpleName() + " salvo com sucesso");
		} catch (Exception e) {
			e.printStackTrace();
			if (tx != null && tx.isActive()){
				tx.rollback();
			}
			throw new CpfJaCadastradoException();
		}
	}
	
	
}
